<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Project extends CI_Controller {

    private $_archive_zip_name;
    public function __construct() {
        parent::__construct();
        
        $this->_archive_zip_name = "project.zip";
        $this->load->model('project_model', '', TRUE);
        $this->load->library('zip');
    }

    function index() {

        $history = $this->project_model->getHistory();
        $this->template->set_partial('left_menu', 'left_menu')
                ->set_partial('main_container', 'projects/history_view', array("history" => $history))
                ->set_partial('footer', 'footer')
                ->build('welcome_message');
    }
	
    function add() {
      
        isloged();
        $this->clean();
        $plug = array(
            'custom-plugins/fileinput',
            'plugins/validate/jquery.validate-min',
            'custom-plugins/wizard/wizard.min',
            'custom-plugins/wizard/jquery.form.min',
            // upload
            'plugins/plupload/plupload',
            'plugins/plupload/plupload.flash',
            'plugins/plupload/plupload.html4',
            'plugins/plupload/plupload.html5',
            'plugins/plupload/jquery.plupload.queue/jquery.plupload.queue',
            'plugins/elfinder/js/elfinder.min',
            'js/demo/demo.files'
        );
        $this->template->append_metadata(script($plug));
        $this->template->set_partial('left_menu', 'left_menu')
                ->set_partial('main_container', 'projects/create_project')
                ->set_partial('footer', 'footer')
                ->build('welcome_message');
    }

    function upload_resources() {
        $config['upload_path'] = RESOURCES_SVG;
        $config['allowed_types'] = 'zip';
        $config['overwrite'] = true;
        $data = array();

        $this->form_validation->set_rules('projname', 'nom du projet', 'required|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $data['success'] = '0';
            $data['errors'] = form_error('projname');
            echo json_encode($data);
            exit();
        }
        $config2['upload_path'] 	= 	IMG_LOGO_PATH;
        $config2['allowed_types'] 	= 	'png|jpg|jpeg';
        $config2['overwrite'] 		= 	true;
        $config2['file_name'] 		= 	"logo.png";
        
        $this->load->library('upload', $config2);
        $logo_file="logofile";
        
        if (!$this->upload->do_upload($logo_file))
        {
            $data['success'] = "0";
            $data['error'] = $this->upload->display_errors();
            echo json_encode($data);
            return;
        }

        //$this->load->library('upload', $config);
        $this->upload->initialize($config);
        $file_name = "resfile";

        if (!$this->upload->do_upload($file_name)) {
            $data['success'] = "0";
            $data['error'] = $this->upload->display_errors();
            echo json_encode($data);
            return;
        } else {
            $data['project_name'] = $this->input->post('projname');
			$temp = $this->upload->data();
            $data['file_name'] = $temp['file_name'];
            $ret = $this->create_project($data);
            echo json_encode($ret);
        } 
    }

    private function create_project($data) {
        $this->load->helper('my_file');
        $path = IMAGE_PATH;
        $info['success'] = "0";
        if (!is_empty_dir($path)) {
            set_emty_dir($path);
        }
        $this->load->helper('directory');
        $source = RESOURCES_SVG . $data['file_name'];
        if (extract_zip_to($source, $path)) {
            $info['success'] = '1';
            $this->create_menu_code();
        } else {
            $info['error'] = "CAN_NOT_EXTRACT_ARCHIVE";
        }
        return $info;
    }

    function load_attachments() {
        $this->load->helper('my_file');
        $menu = $this->input->get('menu');
        $menu = split_name($menu , TAG_NAME ); // supression du code et de l'extension'
        $data['success'] = 0;
        $this->load->library('upload');
        $files = $_FILES;
        if (!isset($_FILES['attachments'])) {
            $data['error'] = "<li>Auccun fichier selectionné !</li>";
            echo json_encode($data);
            exit();
        }
        $cpt = count($_FILES['attachments']['name']);
        $data = array();
        $error = '';
        $this->load->helper('my_file');
        for ($i = 0; $i < $cpt; $i++) {
            $_FILES['userfile']['name'] = wd_remove_accents($files['attachments']['name'][$i] );
            $_FILES['userfile']['type'] = $files['attachments']['type'][$i];
            $_FILES['userfile']['tmp_name'] = $files['attachments']['tmp_name'][$i];
            $_FILES['userfile']['error'] = $files['attachments']['error'][$i];
            $_FILES['userfile']['size'] = $files['attachments']['size'][$i];
            if (!is_dir(ATTACHMENTS_PATH . $menu)) {
                create_dir(ATTACHMENTS_PATH . $menu , 0777);
            }
			chmod(ATTACHMENTS_PATH . $menu , 0777) ;
			
            $config = $this->set_upload_options($menu);
            $this->upload->initialize($config);
            if (!$this->upload->do_upload()) {
					$data['success'] = 0;
                $error .= $this->upload->display_errors();
            } else {
                $data['success'] = 1;
                if (!isset($data['upload_data']))
                    $data['upload_data'] = array();
                $data['upload_data'][] = $this->upload->data();
            }
        }
        if (!empty($error))
            $data['error'] = $error;
        echo json_encode($data);
    }

    private function set_upload_options($path = NULL) {
        $config = array();
        $config['upload_path'] = ATTACHMENTS_PATH . ( ($path !== NULL) ? $path : '' );
//        $config['allowed_types'] = 'pdf|doc|docx|xls|xlsx|ppt|pptx|zip|rar|vsd';
        $config['allowed_types'] = '*';
        $config['max_size'] = '0'; // 0 = no file size limit
        $config['overwrite'] = TRUE;
        return $config;
    }

    private function step_two($data = null) {

        if ($data == null || !is_array($data))
            return;
        $this->load->helper('my_file');
        $path = PROJECTS_PATH . $data['project_name'];
        if (is_dir($path)) {

            $info['error'] = "Le projet :<u>" . $data['project_name'] . " existe deja !";
        } else {

            if (!create_dir($path , 0777)) {
                $info['error'] = "Des erreur sont survenu pandont la creation du repertoire :$path";
            } else {
                $this->load->helper('directory');
                $source = IMAGE_PATH . $data['resource']['file_name'];
                if (extract_zip_to($source, $path)) 
                {
                    $info['svg_files'] = directory_map($path, 1);
                    $info['file_tree'] = create_tree($info['svg_files']);
                    $info['list'] = create_navigation_menu($info['file_tree']);
                } else {
                    $info['error'] = "le fichier" . $data['resource']['file_name'] . " n'a pas pus être extrait ";
                }
            }
        }

        return $info;
    }

    function attachement() {


        $meta = array(
            'custom-plugins/fileinput',
            'plugins/validate/jquery.validate-min',
            'custom-plugins/wizard/wizard.min',
            'custom-plugins/wizard/jquery.form.min',
            'js/demo/demo.wizard',
            // upload
            'plugins/plupload/plupload',
            'plugins/plupload/plupload.flash',
            'plugins/plupload/plupload.html4',
            'plugins/plupload/plupload.html5',
            'plugins/plupload/jquery.plupload.queue/jquery.plupload.queue',
            'plugins/elfinder/js/elfinder.min',
            'js/demo/demo.files'
        );

        foreach ($meta as $l)
            $this->template->append_metadata(js($l));

        $this->template->set_partial('left_menu', 'left_menu')
                ->set_partial('main_container', 'projects/attachement')
                ->set_partial('footer', 'footer')
                ->build('welcome_message');
    }

    public function constrct_list() {
        $this->load->helper(array('directory', 'my_file'));
        $this->load->model('menu_model','menu');
        $path = IMAGE_PATH;
        $images = directory_map($path, 1);
        $file_tree = create_tree($images);
        $list_items = get_list_items($file_tree);
        $data = array();
        foreach ($list_items as $item)
        {
			$t = $this->menu->get_by(array('code' , $item));
            $data[] = $t[0];
        }
        echo $this->load->view('projects/list_menu', array('list' => $data), true);
    }

    public function create_project_index() {
                
        $this->load->helper('file');
        $menu = get_linked_nav_menu( array('class' => 'navigation'));
        $data = array(
            'menu' => $menu ,
            'default'=>get_default_elemnt(),
            );
        $index_html = $this->load->view('projects/project_index', $data, true);

       return  write_file(CURRENT_PATH . 'index.html', $index_html);
             
    }


    
 public function img_to_html() 
    {
        $this->load->helper(array('my_file', 'directory', 'file' ));
        $this->load->model('menu_model','menu');
        $map =  getAttachment();
      
        foreach ($map as $node) 
        {
          $data = array();
          $main_menu = split_name($node['menu'] , TAG_NAME );
          
          $data['file_name'] = $main_menu;
          $attach_list = directory_map(ATTACHMENTS_PATH.$main_menu , 1);
          if( $attach_list  !== FALSE )
               $data['attach_list'] = $attach_list ;
           else {
               $data['attach_list'] = array() ;
           }
          $data['img_name'] =$node['menu'];
          
   //-----------------  Gestion des map --------------- // 
          
          $data['img_map'] = $this->menu->getMapbyImgName( $data['img_name'] );
          list($width, $height) = getimagesize(IMAGE_PATH.$data['img_name']);
          $data['img_width'] = $width;
          $data['img_height'] = $height;
          
    //-------------- Fin gestion des map -------------- //
          
          $html = $this->load->view('projects/svghtml',  $data, true);
          write_file(CURRENT_PATH . '/ressources/' . $data['file_name'] . '.html', $html);
         
          foreach ($node['attach'] as $child )
          {
             $data_child = array();
             $data_child['attach_list'] = $attach_list;
             $data_child['img_name'] = $child;
             $data_child['file_name'] =  $main_menu;
             
             //-----------------  Gestion des map --------------- //
             
              $data_child['img_map'] = $this->menu->getMapbyImgName( $data_child['img_name'] );
             list($width, $height) = getimagesize(IMAGE_PATH.$data_child['img_name']);
             $data_child['img_width'] = $width;
             $data_child['img_height'] = $height;
             
             //-------------- Fin gestion des map -------------- //
            
             
            $html = $this->load->view('projects/svghtml',  $data_child, true);
            write_file(CURRENT_PATH . '/ressources/' . split_name($child , TAG_NAME ). '.html', $html); 
          }

        }
    }
function create_svg_file($data)
{
    var_dump($data);
     
}

    function step_3()
    {
        $this->load->helper('my_file');
       
      $data = array(
           'menu_nav'=>  create_navigation_menu(create_tree($this->get_liste_title())),
           
           );
       echo $this->load->view('projects/download' , $data);
    }
    
    // recuperer les titre a partire des code
    private function get_liste_title()
    {
        $this->load->model('menu_model','menu');
        $list_of_name = array();
        foreach ( get_liste_names() as $name)
        {
			$t = $this->menu->get_by(array('code' ,$name) );
            $v = $t[0];
            $list_of_name[] = split_name ( $name , TAG_CODE ).' '.$v['title'].'__'.$v['id'];
        }
        return $list_of_name;
        
    }
     
    function download_project()
    {  
        $this->load->helper('my_file');
        $this->create_project_index();
        $this->img_to_html();
        $this->zip->read_dir(CURRENT_PATH, false);
        $this->zip->archive(HISTORY_PATH . $this->_archive_zip_name);
        $this->zip->download();
        //download_zip_file(HISTORY_PATH.$this->_archive_zip_name);
    }
    
    
     private  function clean()
    {
      $this->load->model('menu_model','menu');
      $this->menu->truncat();
      $this->menu->delete_maps();
      $this->load->helper(array('directory' ,'my_file' ) );
       $files = directory_map(CURRENT_PATH , 1);
       $resp = true;
        foreach ($files as $file)
        {
            if(is_file(CURRENT_PATH.$file))
            {
                    $resp = $resp && unlink (CURRENT_PATH.$file);
            }
        }
        
        $files = directory_map(CURRENT_PATH."ressources" , 1);
        foreach ($files as $file)
        {
            $path = CURRENT_PATH."ressources/" ;
            if(is_file( $path.$file))
            {
                   $resp = $resp && unlink ($path.$file);
            }
        }
        $resp = $resp && set_emty_dir( ATTACHMENTS_PATH );
        $resp = $resp && set_emty_dir( IMAGE_PATH );
        $resp = $resp && set_emty_dir( RESOURCES_SVG );
        
        return $resp;
    } 
    
    
    function create_menu_code()
    {
        $this->load->helper('my_file');
        $this->load->model('menu_model','menu');
        
		// supression des element existant
        $this->menu->truncat();
        
        $list_name = get_liste_names();
        $data = array();
        foreach ($list_name as $k=>$list)
        {
            $newname = split_name($list , TAG_CODE).' '.SLUG .'_100'.$k.'.'.split_name($list , TAG_EXT);
            rename(IMAGE_PATH.$list, IMAGE_PATH.$newname);
            $data[] = array(
                'code' =>$newname,
                'title'=> clean_name( split_name( $list , TAG_NAME ) ),
            );
        }
       $this->menu->add($data);
    }
    
    public function update_menu()
    {
         $id = $this->input->post('menu_id');
        $title = $this->input->post('menu_title');
        
        $this->load->library('form_validation');
        $this->load->helper('form');
        $this->form_validation->set_rules('menu_id', 'id', 'xss_clean');
        $this->form_validation->set_rules('menu_title', 'Title', 'xss_clean');
        
        if($this->form_validation->run() === FALSE)
        {
            echo json_encode(array('success'=>'0' , 'error'=>  validation_errors()));
            return;
        }
        $this->load->model('menu_model','menu');
        $ret = $this->menu->update($id , array('title' => $title));
        if($ret)
        {
            echo   json_encode(array('success'=>'1' ));
        }
        else
        {
          echo json_encode(array('success'=>'0' , 'error'=>  'system error' ));   
        }
  
    }
      function deletehistory(){
            $projet_id = $this->input->get('id');
            $this->project_model->deletehistoty($projet_id);
            
            $history = $this->project_model->getHistory();
            $this->template->set_partial('left_menu', 'left_menu')
                ->set_partial('main_container', 'projects/history_view', array("history" => $history))
                ->set_partial('footer', 'footer')
                ->build('welcome_message');
    }
}
